package com.yi.wood.service.impl;

import com.yi.wood.base.Result;
import com.yi.wood.base.ResultCodeEnum;
import com.yi.wood.dao.UserDao;
import com.yi.wood.entity.User;
import com.yi.wood.service.UserService;
import com.yi.wood.service.exception.BusinessException;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author moyi
 * @since 1.0
 */
public abstract class AbstractUserServiceImpl implements UserService {

    @Resource
    protected UserDao userDao;

    @Override
    public User findUserByUserName(String userName) {
        return userDao.findByUserNameEquals(userName);
    }

    @Override
    public User findUserByEmail(String email) {
        User user = new User();
        user.setEmail(email);
        Example<User> example = Example.of(user);
        Optional<User> optionalUser = userDao.findOne(example);
        return optionalUser.orElse(null);
    }

    @Override
    public User findUserByPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        Example<User> example = Example.of(user);
        Optional<User> optionalUser = userDao.findOne(example);
        return optionalUser.orElse(null);
    }

    @Override
    public User addData(User user) {
        User dataUser = findUserByUserName(user.getUserName());
        if (dataUser != null){
            throw new BusinessException(new Result(ResultCodeEnum.DATA_ALREADY_EXISTS,null));
        }
        return userDao.save(user);
    }

    @Override
    public User updateData(User user) {
        return userDao.save(user);
    }

    @Override
    public Page<User> pageDataList(Example<User> example, Pageable pageable) {
        return userDao.findAll(example, pageable);
    }

    @Override
    public void delData(Long id) {

    }
}
